package com.ipcamera.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import com.example.admintor.threehome.R;

import mediatek.android.IoTManager.IoTManagerNative;
import vstc2.nativecaller.NativeCaller;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;

import voice.encoder.DataEncoder;
import voice.encoder.VoicePlayer;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ipcamera.demo.BridgeService.AddCameraInterface;
import com.ipcamera.demo.BridgeService.CallBackMessageInterface;
import com.ipcamera.demo.BridgeService.IpcamClientInterface;
import com.ipcamera.demo.adapter.SearchListAdapter;
import com.ipcamera.demo.utils.ContentCommon;
import com.ipcamera.demo.utils.SystemValue;

public class AddCameraActivity extends Activity implements OnClickListener, AddCameraInterface, OnItemSelectedListener,
        IpcamClientInterface, CallBackMessageInterface {
    SharedPreferences sh;
    Editor ed;
    private static String state = null;

    EditText wifi_name, wifi_passworld;
    Button wifi_peizhi, wifi_close, btn_searchCamera;
    private VoicePlayer player = new VoicePlayer();

    private String wifiName;
    private String currentBssid;
    private String sendMac = null;

    private IoTManagerNative IoTManager;
    private WifiManager mWifiManager;

    private String mConnectedSsid = "";
    private String mConnectedPassword;
    private String mAuthString;
    private byte mAuthMode;
    private byte AuthModeOpen = 0x00;
    private byte AuthModeShared = 0x01;
    private byte AuthModeAutoSwitch = 0x02;
    private byte AuthModeWPA = 0x03;
    private byte AuthModeWPAPSK = 0x04;
    private byte AuthModeWPANone = 0x05;
    private byte AuthModeWPA2 = 0x06;
    private byte AuthModeWPA2PSK = 0x07;
    private byte AuthModeWPA1WPA2 = 0x08;
    private byte AuthModeWPA1PSKWPA2PSK = 0x09;

    private EditText userEdit = null;
    private EditText pwdEdit = null;
    private EditText didEdit = null;
    private TextView textView_top_show = null;
    private Button done;
    private static final int SEARCH_TIME = 3000;
    private int option = ContentCommon.INVALID_OPTION;
    private int CameraType = ContentCommon.CAMERA_TYPE_MJPEG;
    private Button btnSearchCamera;
    private SearchListAdapter listAdapter = null;
    private ProgressDialog progressdlg = null;
    private boolean isSearched;
    private MyBroadCast receiver;
    private WifiManager manager = null;
    private ProgressBar progressBar = null;
    private static final String STR_DID = "did";
    private static final String STR_MSG_PARAM = "msgparam";
    private MyWifiThread myWifiThread = null;
    private boolean blagg = false;
    private Intent intentbrod = null;
    private WifiInfo info = null;
    boolean bthread = true;
    private Button button_play = null;
    private int tag = 0;

    class MyTimerTask extends TimerTask {

        public void run() {
            updateListHandler.sendEmptyMessage(100000);
        }
    }

    ;

    public class MyWifiThread extends Thread {
        @Override
        public void run() {
            while (blagg == true) {
                super.run();

                updateListHandler.sendEmptyMessage(100000);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public class MyBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context arg0, Intent arg1) {

            AddCameraActivity.this.finish();
            Log.d("ip", "AddCameraActivity.this.finish()");
        }

    }

    class StartPPPPThread implements Runnable {
        @Override
        public void run() {
            try {
                Thread.sleep(100);
                startCameraPPPP();
            } catch (Exception e) {

            }
        }
    }

    private void startCameraPPPP() {
        try {
            Thread.sleep(100);
        } catch (Exception e) {
        }

        if (SystemValue.deviceId.toLowerCase().startsWith("vsta")) {
            NativeCaller.StartPPPPExt(SystemValue.deviceId, SystemValue.deviceName, SystemValue.devicePass, 1, "",
                    "EFGFFBBOKAIEGHJAEDHJFEEOHMNGDCNJCDFKAKHLEBJHKEKMCAFCDLLLHAOCJPPMBHMNOMCJKGJEBGGHJHIOMFBDNPKNFEGCEGCBGCALMFOHBCGMFK");
        } else {
            NativeCaller.StartPPPP(SystemValue.deviceId, SystemValue.deviceName, SystemValue.devicePass, 1, "");
        }
        // int result = NativeCaller.StartPPPP(SystemValue.deviceId,
        // SystemValue.deviceName,
        // SystemValue.devicePass,1,"");
        // Log.i("ip", "result:"+result);
    }

    private void stopCameraPPPP() {
        NativeCaller.StopPPPP(SystemValue.deviceId);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.add_camera);
        sh = getSharedPreferences("wifi_setting", Context.MODE_PRIVATE);
        ed = sh.edit();
        progressdlg = new ProgressDialog(this);
        progressdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressdlg.setMessage(getString(R.string.searching_tip));
        listAdapter = new SearchListAdapter(this);
        findView();
        manager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        InitParams();

        BridgeService.setAddCameraInterface(this);
        BridgeService.setCallBackMessage(this);
        receiver = new MyBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("finish");
        registerReceiver(receiver, filter);
        intentbrod = new Intent("drop");

        getWifi();
        IoTManager = new IoTManagerNative();
        IoTManager.InitSmartConnection();
        Find_View();
        On_Click();
    }

    private void Find_View() {
        wifi_name = (EditText) findViewById(R.id.wifi_name);
        wifi_passworld = (EditText) findViewById(R.id.wifi_passworld);
        wifi_peizhi = (Button) findViewById(R.id.wifi_peizhi);
        wifi_close = (Button) findViewById(R.id.wifi_close);
        btn_searchCamera = (Button) findViewById(R.id.btn_searchCamera);
        textView_top_show = (TextView) findViewById(R.id.login_textView1);
        if (wifiName != null) {
            wifi_name.setText(wifiName);
        }
    }

    private void On_Click() {
        wifi_peizhi.setOnClickListener(this);
        btn_searchCamera.setOnClickListener(this);
        wifi_close.setOnClickListener(this);
    }

    private void sendSonic(String mac, final String wifi) {
        byte[] midbytes = null;

        try {
            midbytes = HexString2Bytes(mac);
            printHexString(midbytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (midbytes.length > 6) {
            Toast.makeText(AddCameraActivity.this, "no support", Toast.LENGTH_SHORT).show();
            return;
        }

        byte[] b = null;
        int num = 0;
        if (midbytes.length == 2) {
            b = new byte[]{midbytes[0], midbytes[1]};
            num = 2;
        } else if (midbytes.length == 3) {
            b = new byte[]{midbytes[0], midbytes[1], midbytes[2]};
            num = 3;
        } else if (midbytes.length == 4) {
            b = new byte[]{midbytes[0], midbytes[1], midbytes[2], midbytes[3]};
            num = 4;
        } else if (midbytes.length == 5) {
            b = new byte[]{midbytes[0], midbytes[1], midbytes[2], midbytes[3], midbytes[4]};
            num = 5;
        } else if (midbytes.length == 6) {
            b = new byte[]{midbytes[0], midbytes[1], midbytes[2], midbytes[3], midbytes[4], midbytes[5]};
            num = 6;
        } else if (midbytes.length == 1) {
            b = new byte[]{midbytes[0]};
            num = 1;
        }

        int a[] = new int[19];
        a[0] = 6500;
        int i, j;
        for (i = 0; i < 18; i++) {
            a[i + 1] = a[i] + 200;
        }

        player.setFreqs(a);

        player.play(DataEncoder.encodeMacWiFi(b, wifi.trim()), 5, 1000);

    }

    private void setSmartLink() {
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (mWifiManager.isWifiEnabled()) {
            WifiInfo WifiInfo = mWifiManager.getConnectionInfo();
            mConnectedSsid = WifiInfo.getSSID();
            int iLen = mConnectedSsid.length();
            if (mConnectedSsid.startsWith("\"") && mConnectedSsid.endsWith("\"")) {
                mConnectedSsid = mConnectedSsid.substring(1, iLen - 1);
            }
            List<ScanResult> ScanResultlist = mWifiManager.getScanResults();

            for (int i = 0, len = ScanResultlist.size(); i < len; i++) {
                ScanResult AccessPoint = ScanResultlist.get(i);

                if (AccessPoint.SSID.equals(mConnectedSsid)) {
                    boolean WpaPsk = AccessPoint.capabilities.contains("WPA-PSK");
                    boolean Wpa2Psk = AccessPoint.capabilities.contains("WPA2-PSK");
                    boolean Wpa = AccessPoint.capabilities.contains("WPA-EAP");
                    boolean Wpa2 = AccessPoint.capabilities.contains("WPA2-EAP");

                    if (AccessPoint.capabilities.contains("WEP")) {
                        mAuthString = "OPEN-WEP";
                        mAuthMode = AuthModeOpen;
                        break;
                    }

                    if (WpaPsk && Wpa2Psk) {
                        mAuthString = "WPA-PSK WPA2-PSK";
                        mAuthMode = AuthModeWPA1PSKWPA2PSK;
                        break;
                    } else if (Wpa2Psk) {
                        mAuthString = "WPA2-PSK";
                        mAuthMode = AuthModeWPA2PSK;
                        break;
                    } else if (WpaPsk) {
                        mAuthString = "WPA-PSK";
                        mAuthMode = AuthModeWPAPSK;
                        break;
                    }

                    if (Wpa && Wpa2) {
                        mAuthString = "WPA-EAP WPA2-EAP";
                        mAuthMode = AuthModeWPA1WPA2;
                        break;
                    } else if (Wpa2) {
                        mAuthString = "WPA2-EAP";
                        mAuthMode = AuthModeWPA2;
                        break;
                    } else if (Wpa) {
                        mAuthString = "WPA-EAP";
                        mAuthMode = AuthModeWPA;
                        break;
                    }

                    mAuthString = "OPEN";
                    mAuthMode = AuthModeOpen;

                }
            }

        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (!sh.getString("passworld", "null").equals("null")) {
            didEdit.setText(sh.getString("ID", "null"));
            pwdEdit.setText(sh.getString("passworld", "null"));
            wifi_passworld.setText(sh.getString("wifi_passworld", "null"));
        }
        if (!(state == null)) {
            textView_top_show.setBackgroundColor(Color.WHITE);
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        blagg = true;
    }

    private void InitParams() {

        done.setOnClickListener(this);
        btnSearchCamera.setOnClickListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (myWifiThread != null) {
            blagg = false;
        }
        progressdlg.dismiss();
        NativeCaller.StopSearch();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // System.out.println("视频界面结束了！！！");
        unregisterReceiver(receiver);
        // NativeCaller.Free();
        // Intent intent = new Intent();
        // intent.setClass(this, BridgeService.class);
        // stopService(intent);
        // tag = 0;
    }

    Runnable updateThread = new Runnable() {

        public void run() {
            NativeCaller.StopSearch();
            progressdlg.dismiss();
            Message msg = updateListHandler.obtainMessage();
            msg.what = 1;
            updateListHandler.sendMessage(msg);
        }
    };

    Handler updateListHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                listAdapter.notifyDataSetChanged();
                if (listAdapter.getCount() > 0) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(AddCameraActivity.this);
                    dialog.setTitle(getResources().getString(R.string.add_search_result));
                    dialog.setPositiveButton(getResources().getString(R.string.refresh),
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startSearch();
                                }
                            });
                    dialog.setNegativeButton(getResources().getString(R.string.str_cancel), null);
                    dialog.setAdapter(listAdapter, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int arg2) {
                            Map<String, Object> mapItem = (Map<String, Object>) listAdapter.getItemContent(arg2);
                            if (mapItem == null) {
                                return;
                            }

                            String strName = (String) mapItem.get(ContentCommon.STR_CAMERA_NAME);
                            String strDID = (String) mapItem.get(ContentCommon.STR_CAMERA_ID);
                            String strUser = ContentCommon.DEFAULT_USER_NAME;
                            String strPwd = ContentCommon.DEFAULT_USER_PWD;
                            userEdit.setText(strUser);
                            pwdEdit.setText(strPwd);
                            didEdit.setText(strDID);

                        }
                    });

                    dialog.show();
                } else {
                    Toast.makeText(AddCameraActivity.this, getResources().getString(R.string.add_search_no),
                            Toast.LENGTH_LONG).show();
                    isSearched = false;//
                }
            }

            if (msg.what == 2) {
            }

        }
    };

    public static String int2ip(long ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    private void startSearch() {
        listAdapter.ClearAll();
        progressdlg.setMessage(getString(R.string.searching_tip));
        progressdlg.show();
        new Thread(new SearchThread()).start();
        updateListHandler.postDelayed(updateThread, SEARCH_TIME);
    }

    private class SearchThread implements Runnable {
        @Override
        public void run() {
            Log.d("tag", "startSearch");
            NativeCaller.StartSearch();
        }
    }

    private void findView() {
        progressBar = (ProgressBar) findViewById(R.id.main_model_progressBar1);
        textView_top_show = (TextView) findViewById(R.id.login_textView1);
        button_play = (Button) findViewById(R.id.play);
        done = (Button) findViewById(R.id.done);
        userEdit = (EditText) findViewById(R.id.editUser);
        pwdEdit = (EditText) findViewById(R.id.editPwd);
        didEdit = (EditText) findViewById(R.id.editDID);
        btnSearchCamera = (Button) findViewById(R.id.btn_searchCamera);

        button_play.setOnClickListener(this);
    }

    /**
     * 鎽勫儚鏈哄湪绾挎椂鍙互鑾峰彇涓�寮犳憚鍍忔満褰撳墠鐨勭敾闈㈠浘
     */
    /*
     * private void getSnapshot(){ String
	 * msg="snapshot.cgi?loginuse=admin&loginpas=" + SystemValue.devicePass +
	 * "&user=admin&pwd=" + SystemValue.devicePass;
	 * NativeCaller.TransferMessage(SystemValue.deviceId, msg, 1); }
	 */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.wifi_close:
                player.stop();
                if (IoTManager != null) {
                    IoTManager.StopSmartConnection();
                }
                break;
            case R.id.wifi_peizhi:
                if (!wifi_name.getText().toString().trim().equals("")
                        && !wifi_passworld.getText().toString().trim().equals("")) {
                    ed.putString("wifi_passworld", wifi_passworld.getText().toString().trim());
                    ed.commit();
                }
                sendSonic(sendMac, wifi_passworld.getText().toString());
                setSmartLink();
                if (!mConnectedSsid.equals("")) {
                    IoTManager.StartSmartConnection(mConnectedSsid, wifi_passworld.getText().toString().trim(),
                            "FF:FF:FF:FF:FF:FF", (byte) mAuthMode);
                }
                break;
            case R.id.play:
                Intent intent = new Intent(AddCameraActivity.this, PlayActivity.class);
                startActivity(intent);
                break;
//            case R.id.setting:
//                if (tag == 1) {
//                    Intent intent1 = new Intent(AddCameraActivity.this, SettingActivity.class);
//                    intent1.putExtra(ContentCommon.STR_CAMERA_ID, SystemValue.deviceId);
//                    intent1.putExtra(ContentCommon.STR_CAMERA_NAME, SystemValue.deviceName);
//                    intent1.putExtra(ContentCommon.STR_CAMERA_PWD, SystemValue.devicePass);
//                    startActivity(intent1);
//                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
//                } else {
//                    Toast.makeText(AddCameraActivity.this, getResources().getString(R.string.main_setting_prompt),
//                            Toast.LENGTH_SHORT).show();
//                }
//                break;
//            case R.id.location_pics_videos:// 鏈湴瑙嗛鍥惧儚
//                if (SystemValue.deviceId != null) {
//                    Intent intent1 = new Intent(AddCameraActivity.this, LocalPictureAndVideoActivity.class);
//                    intent1.putExtra(ContentCommon.STR_CAMERA_ID, SystemValue.deviceId);
//                    intent1.putExtra(ContentCommon.STR_CAMERA_NAME, SystemValue.deviceName);
//                    intent1.putExtra(ContentCommon.STR_CAMERA_PWD, SystemValue.devicePass);
//                    startActivity(intent1);
//                    overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
//                } else {
//                    Toast.makeText(AddCameraActivity.this, "璇风‘璁ゆ槸鍚﹂�夋嫨璁惧", Toast.LENGTH_SHORT).show();
//                }
//                break;
            case R.id.done:
                if (tag == 1) {
                    Toast.makeText(AddCameraActivity.this, "璁惧宸茬粡鏄湪绾跨姸鎬佷簡", Toast.LENGTH_SHORT).show();
                } else if (tag == 2) {
                    Toast.makeText(AddCameraActivity.this, "璁惧涓嶅湪绾�", Toast.LENGTH_SHORT).show();
                } else {
                    if (!didEdit.getText().toString().trim().equals("")
                            && !pwdEdit.getText().toString().trim().equals("")) {
                        ed.putString("ID", didEdit.getText().toString().trim());
                        ed.putString("passworld", pwdEdit.getText().toString().trim());
                        ed.commit();
                    }
                    done();
                }

                break;
            case R.id.btn_searchCamera:
                stopCameraPPPP();
                tag = 0;
//                textView_top_show.setText(R.string.login_stuta_camer);
                SystemValue.deviceId = null;
                searchCamera();
                break;
//            case R.id.btn_linkcamera:
//                Intent it = new Intent(AddCameraActivity.this, LinkCameraSettingActivity.class);
//                it.putExtra(ContentCommon.STR_CAMERA_ID, SystemValue.deviceId);
//                it.putExtra(ContentCommon.STR_CAMERA_NAME, SystemValue.deviceName);
//                it.putExtra(ContentCommon.STR_CAMERA_PWD, SystemValue.devicePass);
//                startActivity(it);
//                break;
            default:
                break;
        }
    }

    private void searchCamera() {
        if (!isSearched) {
            isSearched = true;
            startSearch();
        } else {
            AlertDialog.Builder dialog = new AlertDialog.Builder(AddCameraActivity.this);
            dialog.setTitle(getResources().getString(R.string.add_search_result));
            dialog.setPositiveButton(getResources().getString(R.string.refresh), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startSearch();

                }
            });
            dialog.setNegativeButton(getResources().getString(R.string.str_cancel), null);
            dialog.setAdapter(listAdapter, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int arg2) {
                    Map<String, Object> mapItem = (Map<String, Object>) listAdapter.getItemContent(arg2);
                    if (mapItem == null) {
                        return;
                    }

                    String strName = (String) mapItem.get(ContentCommon.STR_CAMERA_NAME);
                    String strDID = (String) mapItem.get(ContentCommon.STR_CAMERA_ID);
                    String strUser = ContentCommon.DEFAULT_USER_NAME;
                    String strPwd = ContentCommon.DEFAULT_USER_PWD;
                    userEdit.setText(strUser);
                    pwdEdit.setText(strPwd);
                    didEdit.setText(strDID);

                }
            });
            dialog.show();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            AddCameraActivity.this.finish();
            return true;
        }
        return false;
    }

    private void done() {
        Intent in = new Intent();
        String strUser = userEdit.getText().toString();
        String strPwd = pwdEdit.getText().toString();
        String strDID = didEdit.getText().toString();

        if (strDID.length() == 0) {
            Toast.makeText(AddCameraActivity.this, getResources().getString(R.string.input_camera_id),
                    Toast.LENGTH_SHORT).show();
            return;
        }

        if (strUser.length() == 0) {
            Toast.makeText(AddCameraActivity.this, getResources().getString(R.string.input_camera_user),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (option == ContentCommon.INVALID_OPTION) {
            option = ContentCommon.ADD_CAMERA;
        }
        in.putExtra(ContentCommon.CAMERA_OPTION, option);
        in.putExtra(ContentCommon.STR_CAMERA_ID, strDID);
        in.putExtra(ContentCommon.STR_CAMERA_USER, strUser);
        in.putExtra(ContentCommon.STR_CAMERA_PWD, strPwd);
        in.putExtra(ContentCommon.STR_CAMERA_TYPE, CameraType);
        progressBar.setVisibility(View.VISIBLE);
        SystemValue.deviceName = strUser;
        SystemValue.deviceId = strDID;
        SystemValue.devicePass = strPwd;
        BridgeService.setIpcamClientInterface(this);
        NativeCaller.Init();
        new Thread(new StartPPPPThread()).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            didEdit.setText(scanResult);
        }
    }

    /**
     * BridgeService callback
     **/
    @Override
    public void callBackSearchResultData(int sysver, String strMac, String strName, String strDeviceID,
                                         String strIpAddr, int port) {
        Log.e("AddCameraActivity", strDeviceID + strName);
        if (!listAdapter.AddCamera(strMac, strName, strDeviceID)) {
            return;
        }
    }

    public String getInfoSSID() {

        info = manager.getConnectionInfo();
        String ssid = info.getSSID();
        return ssid;
    }

    public int getInfoIp() {

        info = manager.getConnectionInfo();
        int ip = info.getIpAddress();
        return ip;
    }

    private Handler PPPPMsgHandler = new Handler() {
        public void handleMessage(Message msg) {

            Bundle bd = msg.getData();
            int msgParam = bd.getInt(STR_MSG_PARAM);
            int msgType = msg.what;
            Log.i("aaa", "====" + msgType + "--msgParam:" + msgParam);
            String did = bd.getString(STR_DID);
            switch (msgType) {
                case ContentCommon.PPPP_MSG_TYPE_PPPP_STATUS:
                    int resid;
                    switch (msgParam) {
                        case ContentCommon.PPPP_STATUS_CONNECTING:// 0
                            resid = R.string.pppp_status_connecting;
                            progressBar.setVisibility(View.VISIBLE);
                            tag = 2;
                            break;
                        case ContentCommon.PPPP_STATUS_CONNECT_FAILED:// 3
                            resid = R.string.pppp_status_connect_failed;
                            progressBar.setVisibility(View.GONE);
                            tag = 0;
                            break;
                        case ContentCommon.PPPP_STATUS_DISCONNECT:// 4
                            resid = R.string.pppp_status_disconnect;
                            progressBar.setVisibility(View.GONE);
                            tag = 0;
                            break;
                        case ContentCommon.PPPP_STATUS_INITIALING:// 1
                            resid = R.string.pppp_status_initialing;
                            progressBar.setVisibility(View.VISIBLE);
                            tag = 2;
                            break;
                        case ContentCommon.PPPP_STATUS_INVALID_ID:// 5
                            resid = R.string.pppp_status_invalid_id;
                            progressBar.setVisibility(View.GONE);
                            tag = 0;
                            break;
                        case ContentCommon.PPPP_STATUS_ON_LINE:// 2 鍦ㄧ嚎鐘舵��
                            resid = R.string.pppp_status_online;
                            progressBar.setVisibility(View.GONE);
                            // 鎽勫儚鏈哄湪绾夸箣鍚庤鍙栨憚鍍忔満绫诲瀷
                            String cmd = "get_status.cgi?loginuse=admin&loginpas=" + SystemValue.devicePass + "&user=admin&pwd="
                                    + SystemValue.devicePass;
                            NativeCaller.TransferMessage(did, cmd, 1);
                            tag = 1;
                            break;
                        case ContentCommon.PPPP_STATUS_DEVICE_NOT_ON_LINE:// 6
                            resid = R.string.device_not_on_line;
                            progressBar.setVisibility(View.GONE);
                            tag = 0;
                            break;
                        case ContentCommon.PPPP_STATUS_CONNECT_TIMEOUT:// 7
                            resid = R.string.pppp_status_connect_timeout;
                            progressBar.setVisibility(View.GONE);
                            tag = 0;
                            break;
                        case ContentCommon.PPPP_STATUS_CONNECT_ERRER:// 8
                            resid = R.string.pppp_status_pwd_error;
                            progressBar.setVisibility(View.GONE);
                            tag = 0;
                            break;
                        default:
                            resid = R.string.pppp_status_unknown;
                    }
//					textView_top_show.setText(getResources().getString(resid));
                    textView_top_show.setBackgroundColor(Color.GREEN);
                    state = getResources().getString(resid);
                    if (msgParam == ContentCommon.PPPP_STATUS_ON_LINE) {
                        NativeCaller.PPPPGetSystemParams(did, ContentCommon.MSG_TYPE_GET_PARAMS);
                    }
                    if (msgParam == ContentCommon.PPPP_STATUS_INVALID_ID
                            || msgParam == ContentCommon.PPPP_STATUS_CONNECT_FAILED
                            || msgParam == ContentCommon.PPPP_STATUS_DEVICE_NOT_ON_LINE
                            || msgParam == ContentCommon.PPPP_STATUS_CONNECT_TIMEOUT
                            || msgParam == ContentCommon.PPPP_STATUS_CONNECT_ERRER) {
                        NativeCaller.StopPPPP(did);
                    }
                    break;
                case ContentCommon.PPPP_MSG_TYPE_PPPP_MODE:
                    break;

            }

        }
    };

    @Override
    public void BSMsgNotifyData(String did, int type, int param) {
        Log.d("ip", "type:" + type + " param:" + param);
        Bundle bd = new Bundle();
        Message msg = PPPPMsgHandler.obtainMessage();
        msg.what = type;
        bd.putInt(STR_MSG_PARAM, param);
        bd.putString(STR_DID, did);
        msg.setData(bd);
        PPPPMsgHandler.sendMessage(msg);
        if (type == ContentCommon.PPPP_MSG_TYPE_PPPP_STATUS) {
            intentbrod.putExtra("ifdrop", param);
            sendBroadcast(intentbrod);
        }

    }

    @Override
    public void BSSnapshotNotify(String did, byte[] bImage, int len) {
        // TODO Auto-generated method stub
        Log.i("ip", "BSSnapshotNotify---len" + len);
    }

    @Override
    public void callBackUserParams(String did, String user1, String pwd1, String user2, String pwd2, String user3,
                                   String pwd3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void CameraStatus(String did, int status) {

    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void CallBackGetStatus(String did, String resultPbuf, int cmd) {
        // TODO Auto-generated method stub
        if (cmd == ContentCommon.CGI_IEGET_STATUS) {
            String cameraType = spitValue(resultPbuf, "upnp_status=");
            int intType = Integer.parseInt(cameraType);
            int type14 = (int) (intType >> 16) & 1;// 14浣� 鏉ュ垽鏂槸鍚︽姤璀﹁仈鍔ㄦ憚鍍忔満
            if (intType == 2147483647) {// 鐗规畩鍊�
                type14 = 0;
            }

            if (type14 == 1) {
                updateListHandler.sendEmptyMessage(2);
            }

        }
    }

    private String spitValue(String name, String tag) {
        String[] strs = name.split(";");
        for (int i = 0; i < strs.length; i++) {
            String str1 = strs[i].trim();
            if (str1.startsWith("var")) {
                str1 = str1.substring(4, str1.length());
            }
            if (str1.startsWith(tag)) {
                String result = str1.substring(str1.indexOf("=") + 1);
                return result;
            }
        }
        return -1 + "";
    }

    private static byte[] HexString2Bytes(String src) {
        byte[] ret = new byte[src.length() / 2];
        byte[] tmp = src.getBytes();
        for (int i = 0; i < src.length() / 2; i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }
        return ret;
    }

    private static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }

    private static void printHexString(byte[] b) {
        // System.out.print(hint);
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            System.out.print("aaa" + hex.toUpperCase() + " ");
        }
        System.out.println("");
    }

    private void getWifi() {
        WifiManager wifiMan = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);

        WifiInfo wifiInfo = wifiMan.getConnectionInfo();

        wifiName = wifiInfo.getSSID().toString();
        if (wifiName.length() > 2 && wifiName.charAt(0) == '"' && wifiName.charAt(wifiName.length() - 1) == '"') {
            wifiName = wifiName.substring(1, wifiName.length() - 1);
        }

        List<ScanResult> wifiList = wifiMan.getScanResults();
        ArrayList<String> mList = new ArrayList<String>();
        mList.clear();

        for (int i = 0; i < wifiList.size(); i++) {
            mList.add((wifiList.get(i).BSSID).toString());

        }

        currentBssid = wifiInfo.getBSSID();
        if (currentBssid == null) {
            for (int i = 0; i < wifiList.size(); i++) {
                if ((wifiList.get(i).SSID).toString().equals(wifiName)) {
                    currentBssid = (wifiList.get(i).BSSID).toString();
                    break;
                }
            }
        } else {
            if (currentBssid.equals("00:00:00:00:00:00") || currentBssid.equals("")) {
                for (int i = 0; i < wifiList.size(); i++) {
                    if ((wifiList.get(i).SSID).toString().equals(wifiName)) {
                        currentBssid = (wifiList.get(i).BSSID).toString();
                        break;
                    }
                }
            }
        }
        if (currentBssid == null) {
            finish();
        }

        String tomacaddress[] = currentBssid.split(":");
        int currentLen = currentBssid.split(":").length;

        for (int m = currentLen - 1; m > -1; m--) {
            for (int j = mList.size() - 1; j > -1; j--) {
                if (!currentBssid.equals(mList.get(j))) {
                    String array[] = mList.get(j).split(":");
                    if (!tomacaddress[m].equals(array[m])) {
                        mList.remove(j);//
                    }
                }
            }
            if (mList.size() == 1 || mList.size() == 0) {
                if (m == 5) {
                    sendMac = tomacaddress[m].toString();
                } else if (m == 4) {
                    sendMac = tomacaddress[m].toString() + tomacaddress[m + 1].toString();
                } else {
                    sendMac = tomacaddress[5].toString() + tomacaddress[4].toString() + tomacaddress[3].toString();
                }
                break;
            }
        }
    }

    @Override
    public void finish() {
        if (IoTManager != null) {
            IoTManager.StopSmartConnection();
        }
        super.finish();
    }

}
